<template>
  <div class="cmt-container">
    <h3>发表评论</h3>
    <hr>
    <textarea placeholder="请输入要BB的内容（最多吐槽120字）" maxlength="120" v-model="desc"></textarea>

    <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>

    <div class="cmt-list">
      <div class="cmt-item" v-for="(item, i) in comments" :key="item.id">
        <div class="cmt-title">
          第{{ i+1 }}楼&nbsp;&nbsp;用户：{{ item.name }}&nbsp;&nbsp;发表时间：{{ item.addtime | dateFormat }}
        </div>
        <div class="cmt-body">
          {{ item.desc === 'undefined' ? '此用户很懒，嘛都没说': item.desc }}
        </div>
      </div>

    </div>

    <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from 'mint-ui';
import moment from 'moment'

export default {
  data() {
    return {
      pageIndex: 1, // 默认展示第一页数据
      comments: [], // 所有的评论数据
      pageSize: 5,
      desc: ''
    };
  },
  created() {
    this.getComments();
  },
  methods: {
    getUrl() {
      var url = 'comments?'+'artid_gte='+this.id+'&artid_lte='+this.id+'&'
      var start = (this.pageIndex-1)*this.pageSize
      url += '_start='+start+'&_limit='+this.pageSize+'&_sort=id&_order=DESC'
      return url
    },
    getComments() {
      // 获取评论
      this.$http.get(this.getUrl()).then(result => {
        this.comments = this.comments.concat(result.body)
        }, error => {
          Toast('获取评论失败！')
        })
    },
    getMore() {
      // 加载更多
      this.pageIndex++
      this.getComments()
    },
    postComment() {
      if(this.desc == '') {
        Toast('评论内容不能为空！')
        return
      }
      var comment = {
          artid: this.id,
          desc: this.desc,
          name: 'hwq',
          addtime: moment().format('YYYY-MM-DD HH:mm:ss')
      }
      this.$http.post('comments', comment).then(result => {
        Toast('提交评论成功！')
        this.comments.unshift(comment)
        this.desc = ''
      }, error => {
        Toast('提交评论失败！')
      })
    }
  },
  props: ["id"]
};
</script>

<style lang="scss" scoped>
.cmt-container {
  h3 {
    font-size: 18px;
  }
  textarea {
    font-size: 14px;
    height: 85px;
    margin: 0;
  }

  .cmt-list {
    margin: 5px 0;
    .cmt-item {
      font-size: 13px;
      .cmt-title {
        line-height: 30px;
        background-color: #ccc;
      }
      .cmt-body {
        line-height: 35px;
        text-indent: 2em;
      }
    }
  }
}
</style>
